package handlers

import (
	"chatroom/shared"
	"encoding/json"
	"fmt"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

type MessageHandler struct {
	ch *amqp.Channel
}

func (h *MessageHandler) Handle(msg string) error {
	var chatMsg shared.ChatMsg
	if err := json.Unmarshal([]byte(msg), &chatMsg); err != nil {
		return err
	}
	c, ok := onlineClients[chatMsg.ClientId]
	if !ok {
		return fmt.Errorf("client %s not found", chatMsg.ClientId)
	}
	resp := shared.ChatMsgResponse{
		ClientId:   chatMsg.ClientId,
		ClientName: c.ClientName,
		Message:    chatMsg.Message,
		TimeStamp:  time.Now().Unix(),
	}
	respStr, err := json.Marshal(resp)
	if err != nil {
		return err
	}
	cmd := shared.CommandMsg{
		Command: "newchatmsg",
		Body:    string(respStr),
	}
	cmdStr, err := json.Marshal(cmd)
	if err != nil {
		return err
	}
	h.ch.Publish(
		"amq.fanout",
		"",
		false,
		false,
		amqp.Publishing{
			ContentType: "text/json",
			Body:        cmdStr,
		},
	)
	return nil
}
